package com.springx.examples.showcase.controller;


import com.google.common.collect.Maps;
import com.springx.examples.showcase.common.domain.Message;
import com.springx.examples.showcase.entity.Dictionary;
import com.springx.examples.showcase.enums.DictionaryEnum;
import com.springx.examples.showcase.service.DictionaryService;
import com.springx.examples.showcase.vo.tree.DictionaryVo;
import com.springx.examples.showcase.vo.tree.TreeGridVo;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.EnumSet;
import java.util.Map;

@Controller
@RequestMapping("/dictionary")
public class DictionaryController extends BaseController {


    @Autowired
    private DictionaryService dictionaryService;

    @RequestMapping("/index")
    public String index(Model model) {
        model.addAttribute("statusItems", EnumSet.allOf(DictionaryEnum.IS_ENABLED.class));
        model.addAttribute(CRUMBS_ATTRIBUTE, buildCrumbsMap(null, "系统管理", "数据字典管理"));
        return "/dictionary/index";
    }


    /**
     * 列表页面
     *
     * @return
     */
    @RequestMapping("/list")
    public
    @ResponseBody
    Object list(Long id, Integer page, Integer rows,String text,String status,String  order) throws ServletRequestBindingException {
        Long resultId = (null == id || 0l == id.longValue()) ? -1 : id;
        Map<String, Object> searchParams = or(order);
        searchParams.put("parentId", resultId);
        if(StringUtils.isNotBlank(status)){
            searchParams.put("status", status);
        }
        TreeGridVo treeGridVo = new TreeGridVo();
        if (resultId == -1) {
            if(StringUtils.isNotBlank(text)){
                searchParams.put("text", text);
            }
            PageRequest pageRequest = new PageRequest(null == page ? 1 : page, null == rows ? 10 : rows);
            Page<DictionaryVo> pageResult = dictionaryService.findPage(searchParams, pageRequest);
            treeGridVo.setRows(pageResult.getContent());
            treeGridVo.setTotal(pageResult.getTotalElements());
            return treeGridVo;
        }
        return dictionaryService.findChildren(searchParams);
    }


    @RequestMapping("/insert")
    public
    @ResponseBody
    Message insert(@Valid Dictionary dictionary) {
       String m= dictionaryService.save(dictionary);
        Message message;
        if("ERROR".equals(m)){
            message=new Message(Message.StatusType.ERROR,"编码已存在");
        }else{
            message = new Message(Message.StatusType.SUCCESS, "保存成功");
        }
        return message;
    }


    /**
     * 跳转到edit页面
     *
     * @return
     */
    @RequestMapping("/edit_none")
    public String edit(Long id, Model model, String type) {
        Dictionary dictionary ;
        if ("edit".equals(type)) {
            dictionary = dictionaryService.select(id);//通過id當前bean
            model.addAttribute("dictionary", dictionary);
            if (dictionary.getParentId() != -1) {//根目錄
                Dictionary dic = dictionaryService.select(dictionary.getParentId());//查詢父類
                model.addAttribute("dic", dic);
            }
        }
        if ("add".equals(type)) {
            if (id != 0) {
                dictionary = dictionaryService.select(id);
                model.addAttribute("dic", dictionary);
            }
        }
        return "dictionary/edit";
    }


    @RequestMapping("/update")
    public
    @ResponseBody
    Message update(@Valid Dictionary dictionary) {
        Assert.notNull(dictionary.getId(), "参数错误");
        Dictionary editDictionary = dictionaryService.select(dictionary.getId());
        if (editDictionary != null) {
            if(!(dictionary.getCode()).contains("_")){
             editDictionary.setCode(editDictionary.getCode()+"_"+dictionary.getCode());
            }
            else { editDictionary.setCode(dictionary.getCode());}
            editDictionary.setText(dictionary.getText());
            editDictionary.setDescription(dictionary.getDescription());
            editDictionary.setStatus(dictionary.getStatus());
            editDictionary.setSort(dictionary.getSort());
            editDictionary.setParentId(dictionary.getParentId());
            editDictionary.setCreateDate(new Date());
            dictionaryService.updateByPrimaryKeySelective(editDictionary);
        }
        Message message  = new Message(Message.StatusType.SUCCESS, "修改成功");
        return message;
    }


    @RequestMapping("/delete")
    public
    @ResponseBody
    Message delete(@RequestParam(value = "ids[]") Long[] ids) {
        if (ids.length > 0) {
            dictionaryService.delete(ids);
            Message message = new Message(Message.StatusType.SUCCESS, "删除成功");
            return message;
        }
        return null;
    }

    /*
    * *
    * *组装参数
    * *
     *
     * */
    public static Map<String, Object> parse(Map<String, Object> searchParams) {
        Map<String, Object> searchParam = Maps.newHashMap();

        for (Map.Entry<String, Object> entry : searchParams.entrySet()) {
            // 过滤掉空值
            String key = entry.getKey();
            Object value = entry.getValue();

            if (StringUtils.isBlank(ConvertUtils.convert(value))) {
                continue;
            }
            // 拆分operator与filedAttribute
            String[] names = StringUtils.split(key, "_");
            if (names.length != 2) {
                throw new IllegalArgumentException(key + " is not a valid search filter name");
            }
            String filedName = names[1];
            if ("createDate".equals(filedName)) {//fomat  2012-12-12
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
                value = dateFormat.format(value);
            }
            searchParam.put(filedName, value);
        }

        return searchParam;
    }

     public  static Map<String, Object> or(String order ){
         Map<String, Object> searchParam = Maps.newHashMap();
         if (order==null){
             order="asc";
         }
         if("desc".equals(order)){
             searchParam.put("desc",order);
         }
         if("asc".equals(order)){
             searchParam.put("asc",order);
         }
         return  searchParam;
     }
}
